﻿using System.Linq;
using System.Web.Mvc;
using System.Data.Entity;
using VOD.Models;
using System.Web.Helpers;
using System.Data;

namespace VOD.Areas.Admin.Controllers
{
    [Authorize(Roles="Administrators")]
    public class AlbumController : Controller
    {
        private readonly VODEntities _db = new VODEntities();
        //大图列表
        // GET: /Admin/Album/
        public ActionResult Index()
        {
            var videoHasBigPic = _db.Videos
                .Include(v=>v.VideoCategory)
                .Where(v=>v.HasBigPic && v.Recycled!=1)
                .OrderByDescending(v => v.UpdateDate);
            return View(videoHasBigPic);
        }

        public ActionResult Create()
        {
            var videoWithoutBigPic = _db.Videos
                .Include(v => v.VideoCategory)
                .Where(v => !v.HasBigPic && v.Recycled != 1)
                .OrderByDescending(v => v.UpdateDate);
            return View(videoWithoutBigPic);
        }

        /// <summary>
        /// 上传大图
        /// </summary>
        /// <param name="id">VideoID</param>
        /// <returns></returns>
        public ActionResult UploadBigImg(int id)
        {
            var videoUploadImg = _db.Videos.Find(id);
            return View(videoUploadImg);
        }

        [HttpPost]
        public ActionResult UploadBigImg(int id, FormCollection collection)
        {
            WebImage pic = WebImage.GetImageFromRequest("bigImg");
            SaveImg(pic, id);
            var videoUploadImg = _db.Videos.Find(id);
            videoUploadImg.HasBigPic = true;
            _db.Entry(videoUploadImg).State = EntityState.Modified;
            _db.SaveChanges();
            return View(videoUploadImg);
        }

        private void SaveImg(WebImage pic,int videoID)
        {
            if (pic != null)
            {
                //等比例缩放到230*306左右
                if (pic.Height > 306 || pic.Width > 230)
                {
                    pic = pic.Resize(500, 225);
                }
                var imgFile = videoID.ToString() + ".jpg";
                var picPath = Server.MapPath("~/Content/images/BigPic/" + imgFile);
                pic.Save(picPath, forceCorrectExtension: false);
            }
        }

        public ActionResult Cannel(int id)
        {
            var videoCannelBigImg = _db.Videos.Find(id);
            //删除图片文件

            //保存更改
            videoCannelBigImg.HasBigPic = false;
            _db.Entry(videoCannelBigImg).State = EntityState.Modified;
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            _db.Dispose();
            base.Dispose(disposing);
        }
    }
}
